package com.bodystm.temperature.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bodystm.temperature.bed.Bed;
import com.bodystm.temperature.bed.BedService;
import com.bodystm.temperature.patient.Patient;
import com.bodystm.temperature.patient.PatientService;
import com.bodystm.temperature.server.Temperature;
import com.bodystm.temperature.server.TemperatureService;
import com.bodystm.temperature.web.EasyUiMessage;
import com.mimosa.util.datetime.DateFormatUtil;

@Controller
@RequestMapping("/show")
public class ShowController {
	@Resource
	private TemperatureService temperatureService;

	@Resource
	private PatientService patientService;

	@Resource
	private BedService bedService;

	static final String DATE_PATTERN = "yyyy-MM-dd";
	/**
	 * 鏃ュ織璁板綍
	 */
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@RequestMapping("/index.action")
	public String index(Patient patient, Model model) {
		patient = this.patientService.getEntity(patient.getId());
		model.addAttribute("patient", patient);
		return "show/index";
	}

	@RequestMapping("/print.action")
	public String print(Patient patient) {
		return "show/print";
	}

	static final String LONG_FORMAT_DATE = "yyyy-MM-dd HH:mm:ss";

	@RequestMapping("/newPoint.action")
	@ResponseBody
	public String newPoint(String lastTime, String equipNo) {
		Date lastDate = null;
		if (StringUtils.isNotBlank(lastTime)) {
			lastDate = DateFormatUtil.parseDate(lastTime, LONG_FORMAT_DATE);
		}
		if (lastDate == null) {
			lastDate = new Date();
		}
		Temperature temperature = this.temperatureService.getLatestPoint(lastDate, equipNo);
		String data = "[]";
		if (temperature != null) {
			data = String.format("[\"%s\",%f]", DateFormatUtils.format(temperature.getMeasureTime(), LONG_FORMAT_DATE),
					temperature.getMeasureNumOne());
		}
		EasyUiMessage message = new EasyUiMessage();
		message.setData(data);
		return message.toString();
	}

	@RequestMapping("/export.action")
	public String export(Patient queryPatient, Integer distance, Model model) throws ParseException {
		Patient resultPatient = this.patientService.getEntity(queryPatient.getId());
		// 鑾峰彇搴婁綅淇℃伅
		Bed bed = this.bedService.getEntity(resultPatient.getBed().getId());
		// 鑾峰彇鏈�繎鍑犲ぉ鐨勬暟鎹�
		if (distance == null || distance < 1) {
			distance = 7;
		}
		Date maxMeasureDate = this.temperatureService.getLatestDate(resultPatient, distance);
		List<Object> tiwenResultList = null;
		if (maxMeasureDate != null) {
			tiwenResultList = this.temperatureService.getLatestRecord(resultPatient, maxMeasureDate, distance);
		} else {
			tiwenResultList = Collections.emptyList();
			maxMeasureDate = new Date();
		}
		// 璁＄畻浣忛櫌澶╂暟
		int daysIn = (int) ((maxMeasureDate.getTime() - resultPatient.getStartTime().getTime())
				/ DateUtils.MILLIS_PER_DAY);
		// 璁＄畻浣撴俯鐐逛俊鎭�
		long startTime = maxMeasureDate.getTime() - distance * DateUtils.MILLIS_PER_DAY;
		Date date = null;
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = null;
		Map<String, Integer> dateList = new LinkedHashMap<String, Integer>(distance);
		for (int i = 0; i < distance; i++) {
			startTime = startTime + DateUtils.MILLIS_PER_DAY;
			date = new Date(startTime);
			dateStr = dateFormat.format(date);

			dateList.put(dateStr, i);
		}

		Object[] values = null;
		byte[][] resultArray = new byte[distance * 6][8 * 5];// distance*5
		String hour = null;
		int xIndex = 0, yIndex = 0;
		DateFormat hourFormat = new SimpleDateFormat("HH");
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (Object obj : tiwenResultList) {
			values = (Object[]) obj;
			// by rxz 20160219
			calendar.setTime(sdf.parse(values[1].toString()));
			if (calendar.get(Calendar.HOUR_OF_DAY) % 2 != 0)
				continue;
			// by rxz 20160219
			logger.info("tiwen : {}, date : {}", values);
			dateStr = dateFormat.format(values[1]);
			xIndex = dateList.get(dateStr) * 6;
			hour = hourFormat.format(values[1]);
			switch (hour) {
			case "02":
				break;
			case "06":
				xIndex += 1;
				break;
			case "10":
				xIndex += 2;
				break;
			case "14":
				xIndex += 3;
				break;
			case "18":
				xIndex += 4;
				break;
			case "22":
				xIndex += 5;
				break;
			default:
				xIndex = -1;
			}
			if (xIndex < 0) {
				continue;
			}
			yIndex = (int) ((42.6 - (Float) values[0]) / 0.2);
			resultArray[xIndex][yIndex] = 1;
		}
		model.addAttribute("daysIn", daysIn);
		model.addAttribute("distance", distance);
		model.addAttribute("patient", resultPatient);
		model.addAttribute("bed", bed);
		model.addAttribute("resultDateList", dateList.keySet());
		model.addAttribute("resultArray", resultArray);

		return "show/export";
	}

	@RequestMapping("/query.action")
	@ResponseBody
	public String query(Patient patient, String startTimeStr, String endTimeStr, Integer rows) {
		Date startTime = null;
		if (StringUtils.isNotBlank(startTimeStr)) {
			startTime = DateFormatUtil.parseDate(startTimeStr, DATE_PATTERN);
		}
		Date endTime = null;
		if (StringUtils.isNotBlank(endTimeStr)) {
			endTime = DateFormatUtil.parseDate(endTimeStr, DATE_PATTERN);
		}
		List<Temperature> resultList = this.temperatureService.query(patient.getEquipNo(), startTime, endTime, rows);
		StringBuilder builder = new StringBuilder("[");
		for (Temperature temp : resultList) {
			builder.append("{\"").append(DateFormatUtils.format(temp.getMeasureTime(), "yyyy-MM-dd HH:mm:ss"));
			builder.append("\":").append(temp.getMeasureNumOne()).append("},");
		}
		// Date date = new Date();
		// for (int i = 0; i < 20; i++) {
		// builder.append("{\"").append(
		// DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
		// builder.append("\":").append(RandomUtils.nextFloat(36, 38))
		// .append("},");
		// }
		if (builder.length() > 1) {
			builder.deleteCharAt(builder.length() - 1);
		}
		builder.append("]");
		EasyUiMessage message = new EasyUiMessage();
		message.setData(builder.toString());
		return message.toString();
	}
}